package com.cola.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cola.common.CookieConstant;
import com.cola.dao.CommonDao;
import com.cola.entity.Customer;
import com.cola.entity.User;
import com.cola.entity.mep.Mep;
import com.cola.entity.order.Order;
import com.cola.entity.shop.Goods;
import com.cola.entity.shop.ShopCar;
import com.cola.enums.SmsType;
import com.cola.service.CommonService;
import com.cola.service.MepService;
import com.cola.service.ShopService;
import com.cola.service.UserService;
import com.cola.utils.CookieUtils;
import com.cola.utils.Struts2Utils;
import com.cola.utils.baiduMap.BaiduMapUtils;
import com.cola.utils.baiduMap.entity.BaiduMapResult;
import com.cola.utils.jedis.JedisCacheDB;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺Action
 * @author Max
 * @since 2017/9/13
 */
public class ShopAction extends BaseAction{
    private final Logger logger =  LoggerFactory.getLogger(getClass());
    private String customer_no;//店铺申美
    private String customer_system_no;//店铺系统编号
    private String customer_name;//店铺名
    private String city;//城市编号
    private String area;//区域编号
    private String address;//地址
    private String customer_mobile;//手机
    private String customer_contact_name;//联系人
    private String customer_img;//主照片
    private String customer_imgs;//照片
    private String channel_type_no;//渠道
    private String shop_size;
    private String goods_no;
    private Integer goods_num;
    private String goods_no_list;
    private String order_json;
    private String mep_no;
    private String order_no;
    private String sms_code;

    /**
     * 代理商订货首页
     * @author Max
     * @since 2017/9/13
     */
    public String shopIndex(){

        User user = getUserInfoFromRedis();

        List<Goods> goodsList = ShopService.getInstance().getGoodsList(user.getAreaNo(),user.getChannelNo());

        List<Map<String,Object>> brandList = CommonService.getInstance().getBrandList();

        List<Map<String,Object>> typeList = CommonService.getInstance().getGoodsTypeList();

        setRequestAttribute("goods_list",goodsList);

        setRequestAttribute("type_list",typeList);

        setRequestAttribute("brand_list",brandList);

        return SUCCESS;
    }

    /**
     * 跳转到购物车页面
     * @author Max
     * @since 2017/9/16
     */
    public String toShopCar(){
        return SUCCESS;
    }

    /**
     * 获取购物车详情页面信息
     * @author Max
     * @since 2017/9/16
     */
    public void getShopCarDetailInfo(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        ShopCar shopCar = ShopService.getInstance().getShopCarDetailInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

        resultMap.put("result","success");

        resultMap.put("shop_car_info",shopCar);

        Struts2Utils.renderJson(resultMap);
    }


    /**
     * 获取购物车信息
     * @author Max
     * @since 2017/9/15
     */
    public void getShopCarInfo(){
        User user = getUserInfoFromRedis();

        ShopCar shopCarInfo = ShopService.getInstance().getShopCarInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","success");

        resultMap.put("shop_car_info",shopCarInfo);

        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 添加商品到购物车
     * @author Max
     * @since 2017/9/15
     */
    public void addToShopCar(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","error");

        if(ShopService.getInstance().addToShopCar(user.getUserId(),goods_no,goods_num)){

            resultMap.put("result","success");

            ShopCar shopCarInfo = ShopService.getInstance().getShopCarInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

            resultMap.put("shop_car_info",shopCarInfo);
        }

        Struts2Utils.renderJson(resultMap);
    }


    /**
     * 从购物车删除商品
     * @author Max
     * @since 2017/9/15
     */
    public void subFromShopCar(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","error");

        if(ShopService.getInstance().subFromShopCar(user.getUserId(),goods_no,goods_num)){

            resultMap.put("result","success");

            ShopCar shopCarInfo = ShopService.getInstance().getShopCarInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

            resultMap.put("shop_car_info",shopCarInfo);
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 添加商品到购物车
     * @author Max
     * @since 2017/9/15
     */
    public void addToShopCarDetail(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","error");

        if(ShopService.getInstance().addToShopCar(user.getUserId(),goods_no,goods_num)){

            resultMap.put("result","success");

            ShopCar shopCarInfo = ShopService.getInstance().getShopCarDetailInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

            resultMap.put("shop_car_info",shopCarInfo);
        }
        Struts2Utils.renderJson(resultMap);
    }


    /**
     * 从购物车删除商品
     * @author Max
     * @since 2017/9/15
     */
    public void subFromShopCarDetail(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","error");

        if(ShopService.getInstance().subFromShopCar(user.getUserId(),goods_no,goods_num)){

            resultMap.put("result","success");

            ShopCar shopCarInfo = ShopService.getInstance().getShopCarDetailInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo());

            resultMap.put("shop_car_info",shopCarInfo);
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 清空购物车
     * @author Max
     * @since 2017/9/18
     */
    public void emptyShopCar(){
        User user = getUserInfoFromRedis();

        Map<String,Object> resultMap = new HashMap<String,Object>();

        resultMap.put("result","error");

        if( ShopService.getInstance().emptyShopCar(user.getUserId())){

            resultMap.put("result","success");
        }
        Struts2Utils.renderJson(resultMap);
    }


//===================================================订单=====================================================

    /**
     * 跳转到提交订单页面
     * @author Max
     * @since 2017/9/16
     */
    public String toCreateOrder(){
        try{
            User user = getUserInfoFromRedis();
            List<String> goodsNoList = JSONObject.parseObject(goods_no_list,new TypeReference<List<String>>(){});

            //获取用户详细信息
            Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());
            //获取经销商列表
            List<Mep> mepList = ShopService.getInstance().getMepList(customer);

            ShopCar shopCarInfo = ShopService.getInstance().getOrderGoodsDetailInfo(user.getUserId(),user.getAreaNo(),user.getChannelNo(),goodsNoList);

            if(shopCarInfo.getGoods_list().size()<1){
                return SHOP_INDEX;
            }

            setRequestAttribute("shop_car_info",shopCarInfo);

            setRequestAttribute("shop_car_info_json", JSON.toJSONString(shopCarInfo));

            setRequestAttribute("mep_list",mepList);

            setRequestAttribute("customer",customer);
            return SUCCESS;
        }catch (Exception e){
            logger.error("跳转到提交订单页面异常！",e);
            return ERROR_500;
        }
    }


    /**
     * 创建订单
     * @author Max
     * @since 2017/9/16
     */
    public void createOrder(){
        User user = getUserInfoFromRedis();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        try{
            ShopCar shopCarInfo = JSONObject.parseObject(order_json,ShopCar.class);
            //获取用户详细信息
            Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());

            if(ShopService.getInstance().createOrder(customer,shopCarInfo,mep_no)){

                resultMap.put("result","success");
            }

        }catch (Exception e){
            logger.error("创建订单异常！",e);
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 跳转到下单成功页面
     * @author Max
     * @since 2017/9/17
     */
    public String toOrderSuccess(){
        return SUCCESS;
    }


    /**
     * 跳转到订单列表页
     * @author Max
     * @since 2017/9/17
     */
    public String toOrderList(){
        User user = getUserInfoFromRedis();

        List<Order> list =ShopService.getInstance().getAllOrderList(user.getUserId());

        setRequestAttribute("order_list",list);

        return SUCCESS;
    }
    
    /**
     * 获取订单详情
     * @author Max
     * @since 2017/9/17
     */
    public String toOrderDetail(){
        User user = getUserInfoFromRedis();

        if(user.getUserId()!=null){
            Order order = ShopService.getInstance().getOrderInfoByOrderNo(order_no);

            Mep mep = MepService.getInstance().getMeoInfoByMepNo(order.getMep_no());

            setRequestAttribute("order",order);

            setRequestAttribute("mep",mep);

            return SUCCESS;
        }
        return AUTH;
    }

    //===============================个人中心=======================================
    /**
     * 跳转到个人中心页面
     * @author Max
     * @since 2017/9/18
     */
    public String toShopCenter(){
        User user = getUserInfoFromRedis();
        //获取用户详细信息
        Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());

        setRequestAttribute("shop_info",customer);

        return SUCCESS;
    }

    /**
     * 跳转到店铺信息页面
     * @author Max
     * @since 2017/9/18
     */
    public String toShopInfo(){
        User user = getUserInfoFromRedis();
        //获取用户详细信息
        Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());

        setRequestAttribute("channel",CommonService.getInstance().getChannelTypeByNo(customer.getChannel_type_no()));

        setRequestAttribute("shop_info",customer);
        return SUCCESS;
    }

    /**
     * 跳转到编辑店铺信息页面
     * @author Max
     * @since 2017/9/18
     */
    public String toEditShopInfo(){
        User user = getUserInfoFromRedis();
        //获取用户详细信息
        Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());

        setRequestAttribute("channel",CommonService.getInstance().getChannelTypeByNo(customer.getChannel_type_no()));

        setRequestAttribute("shop_info",customer);

        setRequestAttribute("cityAreaList", CommonService.getInstance().getCityAreaList());

        setRequestAttribute("channelList", CommonService.getInstance().getChannelList());
        return SUCCESS;
    }

    /**
     * 保存修改店铺信息
     * @author Max
     * @since 2017/9/18
     */
    public void editShopInfo(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        Customer customer = getCustomerInfo();
       //检查验证码
        if(checkSmsCodeBySmsType(customer_mobile,sms_code, SmsType.RESET_SMS.getValue())>0){
            //检查手机号有没有被注册过
            if(!UserService.getInstance().checkMobile(customer_mobile,customer.getCustomer_id())){
               //获取经纬度
                String city = CommonDao.getInstance().getAreaNameByNo(customer.getCity());
                BaiduMapResult result = BaiduMapUtils.getLocationInfoByAddress(city+customer.getAddress());

                if(result!=null){
                    customer.setCustomer_lat(result.getResult().getLocation().getLat().doubleValue());
                    customer.setCustomer_lng(result.getResult().getLocation().getLng().doubleValue());
                    //更新信息
                    if(ShopService.getInstance().editShopInfo(customer)){
                        resultMap.put("result","success");
                        //清空购物车
                        ShopService.getInstance().emptyShopCar(customer.getCustomer_id());
                        //清空用户缓存
                        emptyUserInfo();
                    }else{
                        resultMap.put("msg","修改异常！");
                    }
                }else{
                    resultMap.put("msg","请将地址补充详细！");
                }
            }else{
                resultMap.put("msg","手机号已经绑定过！");
            }
        }else{
            resultMap.put("msg","验证码错误！");
        }
        Struts2Utils.renderJson(resultMap);
    }

    /**
     * 获取待编辑的用户信息
     * @return Customer
     * @author Max
     * @since 2017/9/18
     */
    private Customer getCustomerInfo(){
        User user = getUserInfoFromRedis();
        Customer customer = new Customer();
        customer.setCustomer_id(user.getUserId());
        customer.setCustomer_name(customer_name);
        customer.setCity(city);
        customer.setArea(area);
        customer.setAddress(address);
        customer.setCustomer_mobile(customer_mobile);
        customer.setCustomer_contact_name(customer_contact_name);
        customer.setCustomer_img(customer_img);
        customer.setChannel_type_no(channel_type_no);
        customer.setShop_size(shop_size);
        return customer;
    }

    /**
     * 跳转到编辑店铺收货地址页面
     * @author Max
     * @since 2017/9/18
     */
    public String toEditAddress(){
        User user = getUserInfoFromRedis();

        Customer customer = UserService.getInstance().getCustomerInfoBySystemNo(user.getSysNo());

        setRequestAttribute("cityAreaList", CommonService.getInstance().getCityAreaList());

        setRequestAttribute("shop_info",customer);
        return SUCCESS;
    }

    /**
     * 修改店铺地址信息
     * @author Max
     * @since 2017/9/18
     */
    public void editShopAddress(){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");

        Customer customer = getCustomerAddressInfo();

        String city = CommonDao.getInstance().getAreaNameByNo(customer.getCity());
        BaiduMapResult result = BaiduMapUtils.getLocationInfoByAddress(city+customer.getAddress());

        if(result!=null){
            customer.setCustomer_lat(result.getResult().getLocation().getLat().doubleValue());
            customer.setCustomer_lng(result.getResult().getLocation().getLng().doubleValue());

            if(ShopService.getInstance().editShopAddressInfo(customer)){
                resultMap.put("result","success");
                //清空购物车
                ShopService.getInstance().emptyShopCar(customer.getCustomer_id());
                //清空用户缓存
                emptyUserInfo();
            }else{
                resultMap.put("msg","修改异常！");
            }
        }else{
            resultMap.put("msg","请填写详细地址信息！");
        }
        Struts2Utils.renderJson(resultMap);
    }



    /**
     * 获取待编辑的用户信息
     * @return Customer
     * @author Max
     * @since 2017/9/18
     */
    private Customer getCustomerAddressInfo(){
        User user = getUserInfoFromRedis();
        Customer customer = new Customer();
        customer.setCustomer_id(user.getUserId());
        customer.setCity(city);
        customer.setArea(area);
        customer.setAddress(address);
        return customer;
    }

    /**
     * 检查验证码是否正确
     * @param mobile 手机号
     * @param code 验证码
     * @param smsType 验证码类型
     * @author Max
     * @return 1:正确 -1：错误 -2:过期
     * @since 2017/9/13
     */
    private Integer checkSmsCodeBySmsType(String mobile,String code,String smsType){
        String cookieKey = getCookieKeyBySmsType(smsType);

        String redisKey = CookieUtils.getCookieValue(getRequest(),cookieKey);

        if(StringUtils.isNotEmpty(redisKey)){
            Object temp = JedisCacheDB.getObject(redisKey);
            if(temp==null){
                return -2;
            }
            if((mobile+code).equals(temp)){
                return 1;
            }else{
                return -1;
            }
        }else{
            return -2;
        }
    }

    //===============================评价============================================
    private Integer speed_score;
    private Integer courier_score;
    private Integer goods_score;
    private String evaluate_content;
    private Integer courier_id;

    /**
     * 订单评价
     * @author Max
     * @since 2017/9/20
     */
    public void doEvaluate(){
        User user = getUserInfoFromRedis();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","error");
        if(user.getUserId()!=null){
            if(ShopService.getInstance().doEvaluate(speed_score, courier_score, goods_score, evaluate_content
                    , order_no, mep_no, courier_id)){
                resultMap.put("result","success");
            }else{
                resultMap.put("msg","评价异常！");
            }
        }
        Struts2Utils.renderJson(resultMap);
    }







    /**
     * 获取CookiesKey
     * @param smsType
     * @return
     * @author Max
     * @since 2017/9/13
     */
    private String getCookieKeyBySmsType(String smsType){
        switch (smsType){
            case "login_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_LOGIN_SMS;
            case "register_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_REGISTER_SMS;
            case "reset_sms":return CookieConstant.COLA_WX_ORDERING_SYSTEM_RESET_SMS;
        }
        return null;
    }


    public String getGoods_no_list() {
        return goods_no_list;
    }

    public void setGoods_no_list(String goods_no_list) {
        this.goods_no_list = goods_no_list;
    }

    public String getGoods_no() {
        return goods_no;
    }

    public void setGoods_no(String goods_no) {
        this.goods_no = goods_no;
    }

    public Integer getGoods_num() {
        return goods_num;
    }

    public void setGoods_num(Integer goods_num) {
        this.goods_num = goods_num;
    }

    public String getOrder_json() {
        return order_json;
    }

    public void setOrder_json(String order_json) {
        this.order_json = order_json;
    }

    public String getMep_no() {
        return mep_no;
    }

    public void setMep_no(String mep_no) {
        this.mep_no = mep_no;
    }

    public String getOrder_no() {
        return order_no;
    }

    public void setOrder_no(String order_no) {
        this.order_no = order_no;
    }

    public Logger getLogger() {
        return logger;
    }

    public String getCustomer_no() {
        return customer_no;
    }

    public void setCustomer_no(String customer_no) {
        this.customer_no = customer_no;
    }

    public String getCustomer_system_no() {
        return customer_system_no;
    }

    public void setCustomer_system_no(String customer_system_no) {
        this.customer_system_no = customer_system_no;
    }

    public String getCustomer_name() {
        return customer_name;
    }

    public void setCustomer_name(String customer_name) {
        this.customer_name = customer_name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCustomer_mobile() {
        return customer_mobile;
    }

    public void setCustomer_mobile(String customer_mobile) {
        this.customer_mobile = customer_mobile;
    }

    public String getCustomer_contact_name() {
        return customer_contact_name;
    }

    public void setCustomer_contact_name(String customer_contact_name) {
        this.customer_contact_name = customer_contact_name;
    }

    public String getCustomer_img() {
        return customer_img;
    }

    public void setCustomer_img(String customer_img) {
        this.customer_img = customer_img;
    }

    public String getCustomer_imgs() {
        return customer_imgs;
    }

    public void setCustomer_imgs(String customer_imgs) {
        this.customer_imgs = customer_imgs;
    }

    public String getChannel_type_no() {
        return channel_type_no;
    }

    public void setChannel_type_no(String channel_type_no) {
        this.channel_type_no = channel_type_no;
    }

    public String getSms_code() {
        return sms_code;
    }

    public void setSms_code(String sms_code) {
        this.sms_code = sms_code;
    }

    public String getShop_size() {
        return shop_size;
    }

    public void setShop_size(String shop_size) {
        this.shop_size = shop_size;
    }

    public Integer getSpeed_score() {
        return speed_score;
    }

    public void setSpeed_score(Integer speed_score) {
        this.speed_score = speed_score;
    }

    public Integer getCourier_score() {
        return courier_score;
    }

    public void setCourier_score(Integer courier_score) {
        this.courier_score = courier_score;
    }

    public Integer getGoods_score() {
        return goods_score;
    }

    public void setGoods_score(Integer goods_score) {
        this.goods_score = goods_score;
    }

    public String getEvaluate_content() {
        return evaluate_content;
    }

    public void setEvaluate_content(String evaluate_content) {
        this.evaluate_content = evaluate_content;
    }

    public Integer getCourier_id() {
        return courier_id;
    }

    public void setCourier_id(Integer courier_id) {
        this.courier_id = courier_id;
    }
}
